<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { isIp } from '@/utils/verify'
import { ElMessage } from 'element-plus'
import { getIp } from '@/api/ip'

const info = reactive({
  title: "IP查询",
  ipInfo: {
	  ip: "",
	  region: "",
	  isp: "",
	  longitude: '',
	  latitude: ''
  }
})
//查询中
const loading = ref(false)

const params = reactive({
  ip: '',
})
//查询
const search = async (type: string) => {
  try {
	loading.value = true;
    //通过点击获取ip信息
    if (type == 'click') {
      //验证是否ip地址
      if (!isIp(params.ip)) {
        ElMessage({
          message: "无效的ip地址",
          type: "warning",
          duration: 1500
        })
        return
      }
    }
    //获取信息
	const result: any = await getIp(params)
	if (result.code == 0) {
	    info.ipInfo = result.data
		params.ip = info.ipInfo?.ip
	} else {
	  ElMessage({
	    message: result.message,
	    type: "warning",
	    duration: 1000
	  })
	}
  } catch (error) {
    console.log(error)
  } finally {
	loading.value = false;
  }
}

onMounted(() => {
  search(params.ip)
})
</script>

<template>
  <div class="flex flex-col flex-1">
    <ToolHeader :title="info.title"></ToolHeader>
    <div class="p-4 rounded-2xl bg-white flex flex-col items-center">
      <div class="flex max-w-3xl">
        <div class="mr-2">
          <el-input v-model="params.ip"></el-input>
        </div>
        <el-button type="primary" @click="search('click')" :loading="loading">查询</el-button>
      </div>
	  <div class="py-4 w-full">
		  <el-descriptions title="您的IP信息" :column="2" border>
		  		  <el-descriptions-item label="IP地址">{{ info.ipInfo.ip }}</el-descriptions-item>
		  		  <el-descriptions-item label="IP运营商">{{ info.ipInfo.isp }}</el-descriptions-item>
				  <el-descriptions-item label="经度">{{ info.ipInfo.longitude }}</el-descriptions-item>
				  <el-descriptions-item label="维度">{{ info.ipInfo.latitude }}</el-descriptions-item>
		  		  <el-descriptions-item label="地理位置">{{ info.ipInfo.region }}</el-descriptions-item>
		  </el-descriptions>
	  </div>
    </div>
	
	<!-- desc -->
	<ToolDetail title="描述">
	  <el-text>
	    查询当前IP基本信息、地理位置等
	  </el-text> 
	</ToolDetail>
  </div>
</template>

<style scoped>
</style>